#!/bin/sh
#
# Copyright (C) 2011-2012 OpenWrt.org
#

[ -e /etc/config/ubootenv ] && exit 0

touch /etc/config/ubootenv

. /lib/uboot-envtools.sh
. /lib/functions.sh

CI_UBIPART=ubi

block_dev_path() {
	local dev_path

	case "$1" in
	/dev/mmcblk*)
		dev_path="$1"
		;;
	PARTLABEL=* | PARTUUID=*)
		dev_path=$(blkid -t "$1" -o device)
		[ -z "${dev_path}" -o $? -ne 0 ] && return 1
		;;
	*)
		return 1;
		;;
	esac

	echo "${dev_path}"
	return 0
}

nand_find_volume() {
	local ubidevdir ubivoldir
	ubidevdir="/sys/devices/virtual/ubi/$1"
	[ ! -d "$ubidevdir" ] && return 1
	for ubivoldir in $ubidevdir/${1}_*; do
		[ ! -d "$ubivoldir" ] && continue
		if [ "$( cat $ubivoldir/name )" = "$2" ]; then
			basename $ubivoldir
			ubi_mknod "$ubivoldir"
			return 0
		fi
	done
}

nand_find_ubi() {
	local ubidevdir ubidev mtdnum
	mtdnum="$( find_mtd_index $1 )"
	[ ! "$mtdnum" ] && return 1
	for ubidevdir in /sys/devices/virtual/ubi/ubi*; do
		[ ! -d "$ubidevdir" ] && continue
		cmtdnum="$( cat $ubidevdir/mtd_num )"
		[ ! "$mtdnum" ] && continue
		if [ "$mtdnum" = "$cmtdnum" ]; then
			ubidev=$( basename $ubidevdir )
			ubi_mknod "$ubidevdir"
			echo $ubidev
			return 0
		fi
	done
}

board=$(board_name)

case "$board" in
mediatek,*-emmc-rfb)
	env_dev=$(cat /sys/module/boot_param/parameters/env_part 2>/dev/null)
	[ -n "$env_dev" ] && env_dev=$(block_dev_path "${env_dev}")
	[ -z "$env_dev" ] && env_dev=$(block_dev_path "PARTLABEL=u-boot-env")
	[ -n "$env_dev" ] && \
		ubootenv_add_uci_config "$env_dev" "0" "0x80000"
	;;

mediatek,*-snand-rfb)
	env_dev=$(cat /sys/module/boot_param/parameters/env_part 2>/dev/null)
	if [ -n "$env_dev" ]; then
		local mtdnum="$( find_mtd_index "$CI_UBIPART" )"
		if [ ! "$mtdnum" ]; then
			echo "cannot find ubi mtd partition $CI_UBIPART"
			return 1
		fi

		local ubidev="$( nand_find_ubi "$CI_UBIPART" )"
		if [ ! "$ubidev" ]; then
			ubiattach -m "$mtdnum"
			sync
			ubidev="$( nand_find_ubi "$CI_UBIPART" )"
		fi

		local env_ubivol="$( nand_find_volume "${ubidev}" ${env_dev} )"
		if [ -n "${env_ubivol}" ]; then
			ubootenv_add_uci_config "/dev/$env_ubivol" "0" "0x80000" "0x80000" 1
		fi
	fi
	;;
esac

config_load ubootenv
config_foreach ubootenv_add_app_config ubootenv

exit 0
